import { useSelector, useDispatch } from 'react-redux';
import { 
  login as loginAction, 
  register as registerAction, 
  logout as logoutAction, 
  getCurrentUser,
  clearError,
  verifyEmail as verifyEmailAction
} from '../store/authSlice';
import { RootState, AppDispatch } from '../store';
import { useCallback } from 'react';

export const useAuth = () => {
  const dispatch = useDispatch<AppDispatch>();
  const { user, isAuthenticated, isLoading, error } = useSelector(
    (state: RootState) => state.auth
  );

  // 登录
  const login = useCallback(
    async (username: string, password: string) => {
      try {
        const resultAction = await dispatch(loginAction({ username, password }));
        if (loginAction.fulfilled.match(resultAction)) {
          return { success: true };
        } else {
          return { 
            success: false, 
            error: resultAction.payload as string 
          };
        }
      } catch (error) {
        return { 
          success: false, 
          error: error instanceof Error ? error.message : '登录失败'
        };
      }
    },
    [dispatch]
  );

  // 注册
  const register = useCallback(
    async (username: string, email: string, password: string) => {
      try {
        const resultAction = await dispatch(registerAction({ username, email, password }));
        if (registerAction.fulfilled.match(resultAction)) {
          return { success: true };
        } else {
          return { 
            success: false, 
            error: resultAction.payload as string 
          };
        }
      } catch (error) {
        return { 
          success: false, 
          error: error instanceof Error ? error.message : '注册失败'
        };
      }
    },
    [dispatch]
  );

  // 验证邮箱
  const verifyEmail = useCallback(
    async (token: string) => {
      try {
        const resultAction = await dispatch(verifyEmailAction(token));
        if (verifyEmailAction.fulfilled.match(resultAction)) {
          return resultAction.payload;
        } else {
          return { 
            status: 'error' as const,
            message: resultAction.payload as string 
          };
        }
      } catch (error) {
        return { 
          status: 'error' as const,
          message: error instanceof Error ? error.message : '邮箱验证失败'
        };
      }
    },
    [dispatch]
  );

  // 退出登录
  const logout = useCallback(() => {
    dispatch(logoutAction());
  }, [dispatch]);

  // 获取当前用户信息
  const fetchCurrentUser = useCallback(async () => {
    try {
      const resultAction = await dispatch(getCurrentUser());
      return getCurrentUser.fulfilled.match(resultAction);
    } catch (error) {
      return false;
    }
  }, [dispatch]);

  // 清除错误
  const resetError = useCallback(() => {
    dispatch(clearError());
  }, [dispatch]);

  // 检查是否有特定权限
  const hasPermission = useCallback(
    (permissionCode: string) => {
      if (!user || !user.permissions) {
        console.log('权限检查：用户或权限列表不存在', { user });
        return false;
      }
      const hasPermission = user.permissions.includes(permissionCode);
      console.log('权限检查结果:', {
        permissionCode,
        userPermissions: user.permissions,
        hasPermission
      });
      return hasPermission;
    },
    [user]
  );

  // 检查是否有特定角色
  const hasRole = useCallback(
    (roleCode: string) => {
      if (!user || !user.roles) {
        console.log('角色检查：用户或角色列表不存在', { user });
        return false;
      }
      const hasRole = user.roles.some(role => role.code === roleCode);
      console.log('角色检查结果:', {
        roleCode,
        userRoles: user.roles,
        hasRole
      });
      return hasRole;
    },
    [user]
  );

  return {
    user,
    isAuthenticated,
    isLoading,
    error,
    login,
    register,
    verifyEmail,
    logout,
    fetchCurrentUser,
    resetError,
    hasPermission,
    hasRole,
  };
}; 